/**
 * 
 */
package net.phoenix.repository;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

import javax.jcr.AccessDeniedException;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;

import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.TreeBidiMap;

/**
 * @author lixf
 * 
 */
public class BasicNamespaceRegistry implements NamespaceRegistry {
	private BidiMap mapping;
	public BasicNamespaceRegistry() throws IOException {
		Properties properties = new Properties();
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("jigsaw-namespaces.properties");
		properties.load(is);
		is.close();
		this.mapping = new TreeBidiMap(properties);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#registerNamespace(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public void registerNamespace(String prefix, String uri) throws NamespaceException, UnsupportedRepositoryOperationException, AccessDeniedException, RepositoryException {
		this.mapping.put(prefix, uri);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#unregisterNamespace(java.lang.String)
	 */
	@Override
	public void unregisterNamespace(String prefix) throws NamespaceException, UnsupportedRepositoryOperationException, AccessDeniedException, RepositoryException {
		this.mapping.remove(prefix);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#getPrefixes()
	 */
	@Override
	public String[] getPrefixes() throws RepositoryException {
		@SuppressWarnings("unchecked")
		Collection<String> keys = this.mapping.keySet();
		return (String[])keys.toArray(new String[keys.size()]);
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#getURIs()
	 */
	@Override
	public String[] getURIs() throws RepositoryException {
		@SuppressWarnings("unchecked")
		Collection<String> values = this.mapping.values();
		return (String[])values.toArray(new String[values.size()]);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#getURI(java.lang.String)
	 */
	@Override
	public String getURI(String prefix) throws NamespaceException, RepositoryException {
		return (String)this.mapping.get(prefix);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.NamespaceRegistry#getPrefix(java.lang.String)
	 */
	@Override
	public String getPrefix(String uri) throws NamespaceException, RepositoryException {
		return (String)this.mapping.getKey(uri);
	}

}
